<template>
  <div class="home-page">
    <basic-layout />
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import BasicLayout from "@/layouts/BasicLayout.vue"
import { showErrorToast } from "@/utils/toast"
import { getCurrentUser } from "@/api/user"
import useUserStore from "@/stores/user"
import useMenuStore from "@/stores/menu"
import { getTreeMenu } from "@/api/menu"
import { addMenuTab, getFirstMenu, mapMenusToRoutes } from "@/utils/menu"
import { MENU_LIST } from "@/constants"

const router = useRouter()
const route = useRoute()

const userStore = useUserStore()
const menuStore = useMenuStore()

onMounted(() => {
  getCurrentUserInfo()
  getMenu()
})

/**
 * 获取当前用户信息
 */
async function getCurrentUserInfo() {
  try {
    const res = await getCurrentUser()
    if (res.data) {
      userStore.setLoginInfoAction(res.data)
    }
  } catch (error: any) {
    showErrorToast(error.message)
  }
}

/**
 * 获取菜单（树状结构）
 */
async function getMenu() {
  try {
    const res = await getTreeMenu()
    if (res.data) {
      menuStore.setMenuTreeAction(res.data)
      localStorage.setItem(MENU_LIST, JSON.stringify(res.data))

      const routes = mapMenusToRoutes(res.data)
      for (const route of routes) {
        // 动态添加路由
        router.addRoute("home", route)
      }

      // 如果前往的是首页，获取并跳转到第一个菜单
      const menu = getFirstMenu(res.data)
      if (menu && route.path === "/") {
        addMenuTab({
          name: menu.menuName,
          path: menu.path
        })
        router.replace(menu.path)
      }
    }
  } catch (error: any) {
    showErrorToast(error.message)
  }
}
</script>

<style lang="scss" scoped></style>
